package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: xiangfeng
 * @date: 2021年09月29日
 */

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {

        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<E> query = simpleExecutor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if(objects.size()==1){
            return (T) objects.get(0);
        }else{
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }



    /**
     * 使用代理模式的时候，需要namespace的值是接口全限定名，id的值是方法名，
     *  这样做的目的是在getMapper方法中调用selectList或者selectOne的时候，我们通过“接口全限定名.方法名”就
     *  可以确定到具体的mapper配置文件的具体sql：
     *      selectOne(statementId,params)
     * @param mapperClass
     * @param <T>
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理来为DAO接口生成代理对象并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层还是去执行JDBC代码 //根据不同情况，来调用selectList或者selectOne
                //准备参数 1.statementId :sql语句的唯一标识：namespace.id=接口全限定名.方法名
                //获取被调用的方法名
                String methodName = method.getName();
                //获取类的全限定名
                String className = method.getDeclaringClass().getName();

                String statementId = className+"."+methodName;

                String sqlType = configuration.getMappedStatementMap().get(statementId).getSqlType();

                switch (sqlType){
                    case "SELECT":
                        //准备参数2：params:args
                        //获取被调用方法的返回值类型
                        Type genericReturnType = method.getGenericReturnType();
                        if(genericReturnType instanceof ParameterizedType){//判断是否进行了泛型类型参数化
                            List<Object> objects = selectList(statementId, args);
                            return objects;
                        }
                        return selectOne(statementId,args);
                    case "INSERT":
                        insert(statementId,args);
                        return "";
                    case "UPDATE":
                        update(statementId,args);
                        return "";
                    case "DELETE":
                        delete(statementId,args);
                        return "";
                    default:
                        return null;
                }
            }
        });
        return (T) proxyInstance;
    }

    @Override
    public void insert(String statementId, Object... params) throws Exception{
        executeUpdateSql(statementId, params);
    }

    @Override
    public void delete(String statementId, Object... params) throws Exception {
        executeUpdateSql(statementId, params);

    }

    @Override
    public void update(String statementId, Object... params) throws Exception {
        executeUpdateSql(statementId, params);

    }

    private void executeUpdateSql(String statementId, Object[] params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        simpleExecutor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }


}
